package com.miyake.dsp.osa.lab;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import com.miyake.dsp.common.AdjustArraySize;
import com.miyake.dsp.common.CommonTool;


public class Sort {
	public int[] getOutXindex() {
		return index;
	}
	
	public double[] getOutx() {
		return outx;
	}

	public void setOutx(double[] outx) {
		this.outx = outx;
	}

	public double[] getOuty() {
		return outy;
	}

	public void setOuty(double[] outy) {
		this.outy = outy;
	}

	class Tmp {
		public Tmp(int index, double value) {
			this.index = index;
			this.value = value;
		}
		int index;
		double value;
	}

	private double[] outx;
	private double[] outy;
	private int[] index;
	
	public Sort(double[] y) {
		Tmp[] arr = getSortedY(y);
		
		this.outy = new double[arr.length];
		this.index = new int[arr.length];
		for (int i = 0; i < arr.length; i++) {
			int index = arr[i].index;
			this.outy[i] = y[index];
			this.index[i] = index;
		}		
	}
	
	public Sort(double[] x, double[] y) {
		AdjustArraySize a = new AdjustArraySize(x, y);
		x = a.getX1();
		y = a.getX2();
		Tmp[] arr = getSortedY(y);
		
		outx = new double[arr.length];
		outy = new double[arr.length];
		index = new int[arr.length];
		for (int i = 0; i < arr.length; i++) {
			int index = arr[i].index;
			outx[i] = x[index];
			outy[i] = y[index];
			this.index[i] = index;
		}
	}

	private Tmp[] getSortedY(double[] y) {
		List<Tmp> list = new ArrayList<Tmp>();
		for (int i = 0; i < y.length; i++) {
			list.add(new Tmp(i, y[i]));
		}
		Tmp[] arr = list.toArray(new Tmp[0]);
		Arrays.sort(arr, new Comparator<Tmp>() {

			@Override
			public int compare(Tmp o1, Tmp o2) {
				if (o1.value - o2.value > 0) {
					return 1;
				}
				else {
					return -1;
				}
			}
			
		});
		return arr;
	}
	
	
}
